﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using DiscountCoupon.Phone.Common;
using System.Windows.Media.Imaging;
using Microsoft.Xna.Framework.Media;
using System.Windows.Resources;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Tasks;


namespace DiscountCoupon
{
    public partial class CardView : PhoneApplicationPage
    {
        /// <summary>
        /// 缓存管理器
        /// </summary>
        protected IsolateCache cache;
        private string imgId;
        private CouponItemCard info;

        private DownloadHelper dwHelper;
        //指示是否已经加载完成
        private bool IsLoad;
        public CardView()
        {
            InitializeComponent();
            cache = new IsolateCache();
            dwHelper = new DownloadHelper();
            this.Loaded += new RoutedEventHandler(CardView_Loaded);
        }

        void CardView_Loaded(object sender, RoutedEventArgs e)
        {
            string cardIdStr = NavigationContext.QueryString["id"].ToString();
            Guid cardId = new Guid(cardIdStr);
            info = App.ItemCard.Where(o => o.CardId == cardId).FirstOrDefault();
            cardName.Text = info.CardName;
            string key = System.IO.Path.GetFileName(info.CardUrl);
            string originalKey ="0_"+ System.IO.Path.GetFileName(info.CardUrl);
            imgId = key;
            
            Img_View.Stretch = Stretch.Uniform;
            Img_View.VerticalAlignment = VerticalAlignment.Center;

            //原始的图片地址
            if (cache.ContainKey(originalKey))
            {
                BitmapImage img = cache.GetImageFormCache(originalKey);
                Img_View.Source = img;
                IsLoad = true;
            }
            else
            {
                if (cache.ContainKey(key))
                {
                    BitmapImage img = cache.GetImageFormCache(key);
                    Img_View.Source = img;                    
                }
                dwHelper.StartRequest(info.CardUrl, UriKind.Absolute, info, RequestCompletedHandler);
                loadingProgressBar.IsIndeterminate = true;
            }            
        }

        /// <summary>
        /// 下载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void RequestCompletedHandler(object sender, OpenReadCompletedEventArgs args)
        {
            CouponItemCard info = args.UserState as CouponItemCard;
            var fileKey = "0_" + System.IO.Path.GetFileName(info.CardUrl);
            //缓存图片
            if (!cache.ContainKey(fileKey))
            {
                cache.CacheImage(fileKey, args.Result);
            }
            BitmapImage bmp = new BitmapImage();
            bmp.SetSource(args.Result);
            Img_View.Source = bmp;
            IsLoad = true;
            loadingProgressBar.IsIndeterminate = false;
        }
        /// <summary>
        /// 保存优惠券
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveCardImg(object sender, EventArgs e)
        {
            if (!IsLoad)
            {
                MessageBox.Show("图片未加载完成，请稍候...");
            }
            else
            {
                string filePath = cache.CachePath("0_" + imgId);
                try
                {
                    using (
                    IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, System.IO.FileMode.Open,
                        IsolatedStorageFile.GetUserStoreForApplication()))
                    {
                        MediaLibrary library = new MediaLibrary();
                        library.SavePicture("0_" + imgId, stream);
                    }
                    MessageBox.Show("该优惠券已保存到图片库,您可以在需要时从移动设备的图片库中查找。");
                }
                catch
                {
                    MessageBox.Show("优惠券保存失败！");
                }
            }

        }

        /// <summary>
        /// 分享优惠券
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShareCard(object sender, EventArgs e)
        {
            SmsComposeTask smsTask = new SmsComposeTask();
            smsTask.Body = @"Hi,我通过掌中优惠这款软件找了张优惠券，分享给你一下吧!";
            smsTask.Body += info.CardUrl;
            smsTask.Show();
        }
    }
}
